package com.sany.cxp.RabbitMQ.work.fair;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @Author: Thomas
 * @Date: 2024-01-07  20:28:57
 * @Description:
 */
public class Producer {
    public static void main(String[] args) {
        // 1. 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("120.26.196.115");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        // 设置虚拟机节点
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            // 2. 创建连接
            connection = connectionFactory.newConnection("生产者");
            // 3. 通过连接获取通道
            channel = connection.createChannel();
            // 4. 通过通道发送消息
            String queueName = "queue01";
            for (int i = 0; i < 20; i++) {
                String message = "工作模式的轮训机制 -- " + i;
                // 不指定交换机，就会使用默认交换机
                channel.basicPublish("", queueName, null, message.getBytes());
            }
            System.out.println("消息发送成功~");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 8. 关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
